<template>
  <el-dialog width="800px" title="计件工资计算" append-to-body :visible.sync="dialogVisible" @close="handleClose">
    <el-alert style="margin-bottom: 20px" title="计算公式：总产量 x 工序单价 / 员工数" :closable="false" type="warning" />
    <el-form
      ref="submitForm"
      v-loading="formLoading"
      :model="submitForm"
      :rules="submitFormRules"
      label-width="100px"
      label-position="right"
      class="submit-form"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="日期" prop="date">
            <el-date-picker
              v-model="submitForm.date"
              type="date"
              placeholder="请选择日期"
              value-format="yyyy-MM-dd"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="补贴">
            <el-input v-model="submitForm.subsidy" type="number" placeholder="请输入补贴" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="班次" prop="shiftId">
            <el-select v-model="submitForm.shiftId" placeholder="请选择班次">
              <el-option
                v-for="item in shiftList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="总产量">
            <el-input v-model="submitForm.quantity" readonly type="number" placeholder="选择日期和班次后自动显示总产量" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工序" prop="processId">
            <el-select v-model="submitForm.processId" placeholder="请选择工序" @change="processChange">
              <el-option
                v-for="item in processList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工序单价">
            <el-input v-model="submitForm.unitPrice" readonly type="number" placeholder="选择工序后自动显示工序单价" />
          </el-form-item>
        </el-col>
        <el-col v-if="submitForm.processId!==''" :span="24">
          <div>
            <el-form-item label="员工" prop="employeeIds">
              <div v-if="submitForm.employeeIds.length===0">
                <el-button class="el-icon-plus" @click="employeeVisible= true">配置员工</el-button>
              </div>
              <div v-else>
                <el-tag
                  v-for="employee in employeeList"
                  :key="employee.employeeName"
                  style="margin-right: 10px"
                  closable
                  type="primary"
                  :disable-transitions="false"
                  @close="handleRemoveEmployee(employee)"
                >
                  {{ employee.employeeName }}
                </el-tag>
                <el-button size="small" icon="el-icon-plus" @click="addEmployee">添加员工</el-button>
              </div>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row v-if="submitForm.quantity!==''&&submitForm.unitPrice!==''&&submitForm.employeeIds.length>0" style="text-align: center;">
        <el-col :span="8">
          <div style="font-weight: bold;display: inline">共计 </div>
          <div style="color: #EC6E69;font-size: 30px;display: inline">{{ (submitForm.quantity * submitForm.unitPrice).toFixed(2) }}元</div>
        </el-col>
        <el-col :span="8">
          <div style="font-weight: bold;display: inline">个人计件工资&asymp;</div>
          <div style="color: #EC6E69;font-size: 30px;display: inline">{{ (submitForm.quantity * submitForm.unitPrice / submitForm.employeeIds.length).toFixed(2) }}元</div>
        </el-col>
        <el-col :span="8">
          <div style="font-weight: bold;display: inline">个人补贴后&asymp;</div>
          <div style="color: #EC6E69;font-size: 30px;display: inline">{{ (submitForm.quantity * submitForm.unitPrice / submitForm.employeeIds.length + Number(submitForm.subsidy)).toFixed(2) }}元</div>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button :loading="formLoading" type="text" @click="handleClose">取消</el-button>
      <el-button :loading="formLoading" type="primary" @click="handleSubmit">提交</el-button>
    </span>
    <div v-if="employeeVisible">
      <employee-module ref="employeeModule" :disable-ids="submitForm.employeeIds" :visible="employeeVisible" @close="handleCloseEmployee" />
    </div>
  </el-dialog>
</template>

<script>
import { calculatePieceRateWage } from '@/api/financial/pieceRateWage'
import { selectAllShift } from '@/api/erp/shift'
import { selectAllProcess, selectEmployeeByProcessId, updateProcessEmployee } from '@/api/erp/process'
import { selectByShiftIdAndOutputDate } from '@/api/erp/output'
import moment from 'moment'
import EmployeeModule from '@/modules/employeeModule.vue'
/**
 * @author yizuomin
 * @date 2023/5/7 19:05
 **/
export default {
  name: 'CalculateModule',
  components: { EmployeeModule },
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dialogVisible: this.visible,
      employeeVisible: false,
      formLoading: false,
      shiftList: [],
      processList: [],
      submitForm: {
        date: moment(new Date()).format('YYYY-MM-DD'),
        shiftId: '',
        processId: '',
        subsidy: '',
        employeeIds: [],
        quantity: '',
        unitPrice: ''
      },
      submitFormRules: {
        date: [{ required: true, message: '请选择日期', trigger: 'change' }],
        shiftId: [{ required: true, message: '请选择班次', trigger: 'change' }],
        processId: [{ required: true, message: '请选择工序', trigger: 'change' }],
        employeeIds: [{ required: true, message: '请配置员工', trigger: 'change' }]
      },
      employeeList: []
    }
  },
  watch: {
    'submitForm.processId': {
      handler(newVal, oldVal) {
        this.getProcessUnitPrice()
      },
      immediate: true
    },
    'submitForm.date': {
      handler(newVal, oldVal) {
        this.selectByShiftIdAndOutputDate()
      },
      immediate: true
    },
    'submitForm.shiftId': {
      handler(newVal, oldVal) {
        this.selectByShiftIdAndOutputDate()
      },
      immediate: true
    }
  },
  methods: {
    init() {
      this.selectAllShift()
      this.selectAllProcess()
    },
    handleSubmit() {
      this.$refs.submitForm.validate((valid) => {
        if (valid) {
          this.$confirm('请确认当日班次产量数据已录入完毕?重新计算会覆盖之前的计算结果', '提醒', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.formLoading = true
            calculatePieceRateWage(this.submitForm).then(resp => {
              if (resp.success) {
                this.$message.success('操作成功')
                this.$refs.submitForm.resetFields()
                this.handleClose()
              }
            }).finally(() => {
              this.formLoading = false
            })
          })
        }
      })
    },
    processChange(processId) {
      this.formLoading = true
      selectEmployeeByProcessId(processId).then(resp => {
        if (resp.success) {
          this.employeeList = []
          this.submitForm.employeeIds = []
          resp.data.forEach(item => {
            this.employeeList.push(item)
            this.submitForm.employeeIds.push(item.id)
          })
        }
      }).finally(() => {
        this.formLoading = false
      })
    },
    handleClose() {
      this.$emit('close')
    },
    selectAllShift() {
      this.formLoading = true
      selectAllShift().then(resp => {
        if (resp.success) {
          this.shiftList = resp.data
        }
      }).finally(() => {
        this.formLoading = false
      })
    },
    selectAllProcess() {
      this.formLoading = true
      selectAllProcess().then(resp => {
        if (resp.success) {
          this.processList = resp.data
        }
      }).finally(() => {
        this.formLoading = false
      })
    },
    getProcessUnitPrice() {
      if (this.submitForm.processId) {
        this.submitForm.unitPrice = this.processList.filter(e => e.id === this.submitForm.processId)[0].unitPrice
      }
    },
    selectByShiftIdAndOutputDate() {
      if (this.submitForm.date !== '' && this.submitForm.shiftId !== '') {
        this.formLoading = true
        const data = { shiftId: this.submitForm.shiftId, outputDate: this.submitForm.date }
        selectByShiftIdAndOutputDate(data).then(resp => {
          if (resp.success) {
            this.submitForm.quantity = resp.data
          }
        }).finally(() => {
          this.formLoading = false
        })
      }
    },
    handleCloseEmployee(data) {
      this.employeeVisible = false
      if (!data) {
        return
      }
      data.forEach(item => {
        if (this.submitForm.employeeIds.indexOf(item.id) === -1) {
          this.employeeList.push(item)
          this.submitForm.employeeIds.push(item.id)
        } else {
          this.$message.warning('员工:' + item.employeeName + '，已存在，请不要重复选择！')
        }
      })
      this.bindingEmployeeForProcess()
    },
    handleRemoveEmployee(employee) {
      this.employeeList.splice(this.employeeList.indexOf(employee), 1)
      this.submitForm.employeeIds.splice(this.submitForm.employeeIds.indexOf(employee.id), 1)
      this.bindingEmployeeForProcess()
    },
    bindingEmployeeForProcess() {
      this.formLoading = true
      const requestData = { processId: this.submitForm.processId, employeeIds: this.submitForm.employeeIds }
      updateProcessEmployee(requestData).then(resp => {
        if (resp.success) {
          this.$message.success('工序员工配置成功')
        }
      }).finally(() => {
        this.formLoading = false
      })
    },
    addEmployee() {
      this.employeeVisible = true
      this.$nextTick(() => {
        this.$refs.employeeModule.handleSearch()
      })
    }
  }
}
</script>

<style scoped>

</style>
